using System;
using System.Drawing;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI.Design;

namespace OpenSource.Web.WebToolbar
{
	[ToolboxData( "<{0}:WebToolbar runat=server></{0}:WebToolbar>" ),
	DefaultProperty( "Items" ),
	ParseChildren( true, "Items" )]
	public class WebToolbar : CompositeControl
	{
		public WebToolbar()
		{
			//items = new WebToolbarItemCollection();
			items = new List<WebToolbarItem>();
			fixedSizeItems = false;
			itemHeight = 32;
			itemWidth = 32;
			orientation = Orientation.Horizontal;
			beforePostbackScript = "";

		}
		private int itemWidth;
		private int itemHeight;
		private bool fixedSizeItems;
		//private WebToolbarItemCollection items;
		private List<WebToolbarItem> items;
		private bool rightToLeft;
		private string backgroundImage;
		private int itemSpacing;
		private Orientation orientation;
		private string beforePostbackScript;
		private string setStatusTextClientFn;
		HtmlInputHidden eventArgs;

		[Category( "Appearance" )]
		public event WebToolbarClickEventHandler ServerClick;

		//[Bindable(true),
		//Category("Appearance"),
		//DefaultValue(""), Editor(typeof(ImageUrlEditor), typeof(UITypeEditor))]
		//public string S
		//{
		//    get { return s; }
		//    set { s = value; }
		//}
		//private string s;

		[Bindable( true ),
		Category( "Appearance" ),
		DefaultValue( 32 )]
		public int ItemWidth
		{
			get { return itemWidth; }
			set { itemWidth = value; }
		}

		[Bindable( true ),
		Category( "Appearance" ),
		DefaultValue( 32 )]
		public int ItemHeight
		{
			get { return itemHeight; }
			set { itemHeight = value; }
		}

		[Bindable( true ),
		Category( "Appearance" ),
		DefaultValue( false )]
		public bool FixedSizeItems
		{
			get { return fixedSizeItems; }
			set { fixedSizeItems = value; }
		}

		[Bindable( true ),
		Category( "Appearance" ),
		DefaultValue( false )]
		public bool RightToLeft
		{
			get { return rightToLeft; }
			set { rightToLeft = value; }
		}

		[Bindable( true ),
		Category( "Appearance" ),
		DefaultValue( Orientation.Horizontal )]
		public Orientation Orientation
		{
			get { return orientation; }
			set { orientation = value; }
		}

		[Bindable( true ),
		Category( "Appearance" ),
		DefaultValue( 0 )]
		public int ItemSpacing
		{
			get { return itemSpacing; }
			set { itemSpacing = value; }
		}

		[Bindable( true ),
		Category( "Appearance" ),
		DefaultValue( "" ),
		Editor( typeof( ImageUrlEditor ), typeof( UITypeEditor ) )]
		public string BackgroundImage
		{
			get { return backgroundImage; }
			set { backgroundImage = value; }
		}

		[Category( "Behavior" ),
		Description( "The toolbar items collection" ),
		DesignerSerializationVisibility(
			DesignerSerializationVisibility.Content ),
		Editor( typeof( WebToolbarItemCollectionEditor ), typeof( UITypeEditor ) ),
		PersistenceMode( PersistenceMode.InnerDefaultProperty )]
		//public WebToolbarItemCollection Items
		public List<WebToolbarItem> Items
		{
			get { return items; }
		}
		[Category( "Behavior" ),
		DefaultValue( "" )]
		public string BeforePostbackScript
		{
			get { return beforePostbackScript; }
			set { beforePostbackScript = value; }
		}

		[Category( "Behavior" ),
		DefaultValue( "" )]
		public string SetStatusTextClientFn
		{
			get { return setStatusTextClientFn; }
			set { setStatusTextClientFn = value; }
		}

		protected override HtmlTextWriterTag TagKey
		{
			get
			{
				return HtmlTextWriterTag.Div;
			}
		}

		protected override void OnPreRender( EventArgs e )
		{
			if ( !string.IsNullOrEmpty( eventArgs.Value ) )
			{
				WebToolbarItem it = null;
				foreach ( WebToolbarItem item in items )
					if ( item.Name == eventArgs.Value )
					{
						it = item;
						break;
					}
				if ( it != null )
				{
					WebToolbarItemClickEventArgs ev = new WebToolbarItemClickEventArgs( it );
					if ( ServerClick != null )
						ServerClick( this, ev );
				}
			}

			Page.ClientScript.RegisterClientScriptResource( GetType(), "OpenSource.Web.WebToolbar.script.js" );

			string id = ClientID + "js";
			StringBuilder sb = new StringBuilder();
			sb.Append( id ).Append( "=new WebToolbar('" ).Append( ClientID ).Append( "');\r\n" );
			if ( !string.IsNullOrEmpty( setStatusTextClientFn ) )
				sb.Append( id ).Append( ".setStatusFn=" ).Append( setStatusTextClientFn ).Append( ";\r\n" );

			int i = 0;
			foreach ( WebToolbarItem item in items )
			{
				for ( int j = 0; j < items.Count; j++ )
					if ( i != j && items[j].Name == item.Name )
						items[j].Name = string.Empty;
				if ( item.Name == string.Empty )
				{
					int k = 1;
					string n = "item" + k.ToString();
					for ( int j = 0; j < items.Count; j++ )
						if ( i != j && items[j].Name == n )
						{
							j = -1;
							k++;
							n = "item" + k.ToString();
						}
					item.Name = n;
				}

				sb.Append( id ).Append( ".add('" ).Append( ClientID ).Append( item.Name ).Append( "','" );
				sb.Append( item.Name ).Append( "','" );
				sb.Append( item.NormalImgeUrl ).Append( "','" );
				sb.Append( item.HoverImageUrl ).Append( "','" );
				sb.Append( item.PressedImageUrl ).Append( "','" );
				sb.Append( item.DisabledImageUrl ).Append( "'," );
				sb.Append( item.ServerSideClick ? "true" : "false" ).Append( ",'" );
				sb.Append( item.ClientScript ).Append( "'," );
				sb.Append( string.IsNullOrEmpty( item.ConfirmMessage ) ? "null," : "'" + item.ConfirmMessage + "'," );
				sb.Append( item.Enabled ? "true" : "false" ).Append( ",'" );
				sb.Append( string.IsNullOrEmpty( item.StatusText ) ? item.ToolTip : item.StatusText ).Append( "');" );
				i++;
			}
			Page.ClientScript.RegisterClientScriptBlock( GetType(), ClientID + "objects", sb.ToString(), true );

			base.OnPreRender( e );
		}

		protected override void OnLoad( EventArgs e )
		{

			base.OnLoad( e );
		}

		protected override void CreateChildControls()
		{
			eventArgs = new HtmlInputHidden();
			eventArgs.ID = "eventArgs";
			eventArgs.EnableViewState = false;
			Controls.Add( eventArgs );
			
			ChildControlsCreated = true;
			base.CreateChildControls();
		}

		protected override void AddAttributesToRender( HtmlTextWriter writer )
		{
			writer.AddAttribute( HtmlTextWriterAttribute.Dir, rightToLeft ? "rtl" : "ltr" );
			writer.AddStyleAttribute( HtmlTextWriterStyle.Overflow, "hidden" );
			writer.AddAttribute( HtmlTextWriterAttribute.Class, "webtoolbar" );
			base.AddAttributesToRender( writer );
		}
		protected override void RenderContents( HtmlTextWriter writer )
		{
			writer.AddAttribute( "onmouseover", "WebToolbar.MouseOver(event)" );
			writer.AddAttribute( "onmouseout", "WebToolbar.MouseOut(event)" );
			writer.AddAttribute( "onmousedown", "WebToolbar.MouseDown(event)" );
			writer.AddAttribute( "onmouseup", "WebToolbar.MouseUp(event)" );
			writer.AddAttribute( HtmlTextWriterAttribute.Cellpadding, "0" );
			writer.AddAttribute( HtmlTextWriterAttribute.Cellspacing, "0" );
			writer.RenderBeginTag( HtmlTextWriterTag.Table );

			if ( orientation == Orientation.Horizontal )
				writer.RenderBeginTag( HtmlTextWriterTag.Tr );
			foreach ( WebToolbarItem item in Items )
			{
				if ( orientation == Orientation.Vertical )
					writer.RenderBeginTag( HtmlTextWriterTag.Tr );
				writer.AddStyleAttribute( HtmlTextWriterStyle.Width, ItemWidth.ToString() + "px" );
				writer.RenderBeginTag( HtmlTextWriterTag.Td );
				writer.AddAttribute( HtmlTextWriterAttribute.Id, ClientID + item.Name );
				if ( item.Enabled )
					writer.AddAttribute( HtmlTextWriterAttribute.Src, item.NormalImgeUrl );
				else if ( !string.IsNullOrEmpty( item.DisabledImageUrl ) )
					writer.AddAttribute( HtmlTextWriterAttribute.Src, item.DisabledImageUrl );
				else
					writer.AddAttribute( HtmlTextWriterAttribute.Src, item.NormalImgeUrl );
				if ( fixedSizeItems )
				{
					writer.AddAttribute( HtmlTextWriterAttribute.Width, itemWidth.ToString() + "px" );
					writer.AddAttribute( HtmlTextWriterAttribute.Height, itemHeight.ToString() + "px" );
				}
				if ( !string.IsNullOrEmpty( item.ToolTip ) )
					writer.AddAttribute( HtmlTextWriterAttribute.Title, item.ToolTip );
				writer.AddAttribute( HtmlTextWriterAttribute.Class, "wbtitem" );
				writer.AddAttribute( HtmlTextWriterAttribute.Name, item.Name );
				writer.AddStyleAttribute( HtmlTextWriterStyle.Cursor, "hand" );
				writer.RenderBeginTag( HtmlTextWriterTag.Img );
				writer.RenderEndTag();

				writer.RenderEndTag();

				if ( orientation == Orientation.Vertical )
					writer.RenderEndTag();

			}
			if ( orientation == Orientation.Horizontal )
				writer.RenderEndTag();

			writer.RenderEndTag();

			eventArgs.Value = "";
			eventArgs.RenderControl( writer );

			base.RenderContents( writer );
		}

	}

	public class WebToolbarItemClickEventArgs : EventArgs
	{
		public WebToolbarItemClickEventArgs( WebToolbarItem item )
		{
			Item = item;
		}
		public readonly WebToolbarItem Item;
	}

	public delegate void WebToolbarClickEventHandler( object sender, WebToolbarItemClickEventArgs e );
}
